//
//  JMStudyCircleViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/9/5.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMStudyCircleViewController.h"
#import "JMStudyCircleCell.h"
#import "JMStudyCicleViewMode.h"
#import "JMCircleQuestionMode.h"

#import "JMAnswerViewController.h"
#import "JMMyAnswerViewController.h"
#import "JMUpQuestionViewController.h"
#import <UIImageView+WebCache.h>
#import "NSString+date.h"

#import "JMEnlargePictureView.h"



@interface JMStudyCircleViewController ()<UITableViewDataSource,UITableViewDelegate,JMTapImageViewDelegate>{

    int lastId;
}


@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIButton *addBnt;

@property (nonatomic, strong)  UIImage *image;

@property (nonatomic, strong) JMEnlargePictureView *enlargePictureView;

@end

@implementation JMStudyCircleViewController




- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WITH, UI_SCREEN_HEIGHT) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
        
    }
    return _dataArray;
}

- (JMEnlargePictureView *)enlargePictureView
{
    if (!_enlargePictureView) {
        _enlargePictureView = [[JMEnlargePictureView alloc]init];
    }
    return _enlargePictureView;
}

- (UIButton *)addBnt
{
    if (!_addBnt) {
        UIButton *button = [[UIButton alloc]init];
        [button setTitleColor:UIColorFromRGB(0xeb6100) forState:UIControlStateNormal];
        [button addTarget:self action:@selector(submitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setImage:[UIImage imageNamed:@"projectImage.bundle/add_qestion"]forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14.0];
        button.frame = CGRectMake(UI_SCREEN_WITH - 44, 0, 44, 44);
        [self.view addSubview:_addBnt = button];
    }
    return _addBnt;
}
-(void)submitButtonClick:(UIButton *)sender{
    JMUpQuestionViewController *vc = [JMUpQuestionViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.backBtn.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"学习圈";
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:self.addBnt];
    self.navigationItem.rightBarButtonItem =item;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.enlargePictureView];

    lastId = 0;
    [self setupRefresh];
}
#pragma mark 上下拉刷新数据
- (void)setupRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}
-(void)headerRereshing{
    lastId = 0;
    [self getDataFromeServer];
}
-(void)footerRereshing{
    [self getDataFromeServer];
}

-(void)getDataFromeServer{
    [JMTools showAlertView:self.view];
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:[NSString stringWithFormat:@"%d",lastId] forKey:@"last"];
        [dict setObject:@"15"forKey:@"size"];
        [JMStudyCicleViewMode fetchStudeyCiccleMessageParametes:dict block:^(id data, NSError *error, id currData) {
            [JMTools hiddenAlerView:self.view];
            
            
            if([data[@"status"] integerValue] == 1){
                if(lastId == [[currData lastObject] questionId]|| [currData count]== 0){
                    [JMTools showAlertView:self.view message:@"没有更多数据"];
                }else{
                    if(lastId == 0)[self.dataArray removeAllObjects];
                    [self.dataArray addObjectsFromArray:currData];
                    [self.tableView reloadData];
                    lastId = [[currData lastObject] questionId];
                    [JMTools showAlertView:self.view message:data[@"message"]];
                }
            }else{
                [JMTools showAlertView:self.view message:data[@"message"]];
            }
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
        }];
    }
}
#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectio{
    return  self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * str=@"ID";
        JMStudyCircleCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMStudyCircleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
    cell.infoImageView.t_delegate = self;
    [cell.answerBnt addTarget:self action:@selector(answerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.answerBnt.tag = indexPath.row;
    [cell.countBnt addTarget:self action:@selector(countButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.countBnt.tag = indexPath.row;


    JMCircleQuestionMode *mode = [self.dataArray objectAtIndex:indexPath.row];
    [cell.iconImageView  sd_setImageWithURL:[NSURL URLWithString:mode.picString]];
    cell.nameLabel.text = mode.loginString;

    [cell.countBnt setTitle:[NSString stringWithFormat:@"%@人回答",mode.countString]forState:UIControlStateNormal];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:timeZone];
    NSDate *dateTime = [formatter dateFromString:mode.timeString];
    NSDate *dateNow = [NSDate date];
    
    cell.timelabel.text = [NSString dateInterval:dateTime nowDate:dateNow];
    cell.typeLabel.text = [NSString stringWithFormat:@"%@%@",mode.gradeString,mode.subjectString];
    cell.typeLabel.textColor = mode.typeColor;
    cell.typeLabel.layer.borderColor = [mode.typeColor CGColor];
   
    [cell.infoImageView sd_setImageWithURL:[NSURL URLWithString:mode.logoString]];
   
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    JMAnswerViewController *vc = [JMAnswerViewController new];
//    vc.mode = self.dataArray[indexPath.row];
//    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return UI_SCREEN_WITH *0.546875;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (void) tappedWithObject:(JMTapImageView *)sender{
//    UIImageView *iamgeViw = [[UIImageView alloc]initWithFrame:CGRectMake(80, 80, 200, 200)];
//    iamgeViw.image = sender.image;
//    iamgeViw.backgroundColor = [UIColor redColor];
//    [self.view addSubview:iamgeViw];
    
    [self.enlargePictureView showInView:self.view withObject:sender];
}

#pragma mark hui da wen ti
-(void)answerButtonClick:(UIButton *)sender{
    JMMyAnswerViewController *vc = [JMMyAnswerViewController new];
    vc.mode = self.dataArray[sender.tag];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)countButtonClick:(UIButton *)sender{
    JMAnswerViewController *vc = [JMAnswerViewController new];
    vc.mode = self.dataArray[sender.tag];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
